package com.ztom.v2;

/**
 * @author ZhangTao
 */
public class Code42ConvertSortedArrayToBinarySearchTree {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public TreeNode sortedArrayToBST(int[] nums) {
        if (nums == null || nums.length == 0) {
            return null;
        }
        return process(nums, 0, nums.length - 1);
    }

    public TreeNode process(int[] nums, int left, int right) {
        if (left > right) {
            return null;
        }
        // 选中间节点作为 root 来保证高度平衡
        int mid = left + ((right - left) >> 1);
        TreeNode root = new TreeNode(nums[mid]);
        root.left = process(nums, left, mid - 1);
        root.right = process(nums, mid + 1, right);
        return root;
    }
}
